import logging
import time
from contextlib import contextmanager

from django.db.backends.postgresql.base import DatabaseWrapper as DjangoDatabaseWrapper
from django.db.backends.utils import CursorWrapper as DjangoCursorWrapper


@contextmanager
def calc_sql_time(sql):  # noqa: ANN201
    timestamp = time.monotonic()

    yield
    logging.basicConfig(format="%(message)s", level=logging.INFO)
    time_var = f"{time.monotonic() - timestamp:.3f}"
    logging.info("Продолжительность SQL-запроса %s - %s", sql, time_var)


class CursorWrapper(DjangoCursorWrapper):
    def execute(self, sql, params=None):  # noqa: ANN201
        with calc_sql_time(sql):
            return super().execute(sql, params)


class DatabaseWrapper(DjangoDatabaseWrapper):
    def create_cursor(self, name=None) -> CursorWrapper:
        cursor = super().create_cursor(name)
        return CursorWrapper(cursor, self)
